<template>
  <div class="template-puzzle">
    <!-- 左侧工具栏 -->
    <div class="left-panel">
      <!-- 模板导航 -->
      <div class="template-nav">
        <div class="nav-item" 
          v-for="(nav, index) in templateTypes" 
          :key="index"
          :class="{'active': selectedNav === nav}"
          @click="selectNav(nav)">
          {{ nav }}格
        </div>
        <div class="nav-item bizarre"
          :class="{'active': showBizarre}"
          @click="toggleBizarre">
          异形
        </div>
      </div>

      <!-- 模板列表 -->
      <div class="template-list">
        <div class="template-item"
          v-for="(template, index) in filteredTemplates" 
          :key="index"
          :class="{'active': selectedTemplate === template}"
          @click="selectTemplate(template)">
          <img :src="selectedTemplate === template ? template.activeIcon : template.icon" 
               :alt="'模板'+(index+1)">
        </div>
      </div>
    </div>

    <!-- 中间画布区域 -->
    <div class="canvas-area">
      <canvas ref="canvas" id="myCanvas"></canvas>
      
      <!-- 上传提示 -->
      <div class="upload-tip" v-if="!hasImages">
        <div class="tip-text">点击或拖拽图片到此处上传</div>
        <input type="file" 
          ref="fileInput"
          multiple
          accept="image/*"
          @change="handleFileUpload"
          style="display:none">
        <button class="upload-btn" @click="triggerUpload">选择图片</button>
      </div>
    </div>

    <!-- 右侧设置面板 -->
    <div class="right-panel">
      <!-- 画布设置 -->
      <div class="canvas-settings">
        <h3>画布设置</h3>
        <div class="setting-item">
          <span>边距:</span>
          <el-slider v-model="canvasConfig.margin" :min="0" :max="100"/>
        </div>
        <div class="setting-item">
          <span>间距:</span>
          <el-slider v-model="canvasConfig.padding" :min="0" :max="100"/>
        </div>
        <div class="setting-item">
          <span>圆角:</span>
          <el-slider v-model="canvasConfig.radius" :min="0" :max="100"/>
        </div>
      </div>

      <!-- 图片设置 -->
      <div class="image-settings" v-if="selectedPolygon">
        <h3>图片设置</h3>
        <div class="setting-item">
          <span>旋转:</span>
          <el-slider v-model="imageConfig.rotate" :min="0" :max="360"/>
        </div>
        <div class="setting-item">
          <span>缩放:</span>
          <el-slider v-model="imageConfig.scale" :min="50" :max="200" :step="1"/>
        </div>
        <div class="setting-item">
          <span>透明度:</span>
          <el-slider v-model="imageConfig.opacity" :min="0" :max="100" :step="1"/>
        </div>
        
        <div class="operation-btns">
          <button @click="replaceImage">替换图片</button>
          <button @click="deleteImage">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import pintu from '../utils/pintu'

// 模板类型列表
const templateTypes = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 27]

// 当前选择的导航和模板
const selectedNav = ref(2)
const showBizarre = ref(false)
const selectedTemplate = ref(null)

// 画布配置
const canvasConfig = reactive({
  margin: 20,
  padding: 20, 
  radius: 0,
  backgroundColor: "#fff",
  backgroundImage: null,
  borderImage: null,
  isLoop: false,
  cutRatio: 0.3,
  iconSize: 50,
  dragSize: 16,
  lineWidth: 8,
  lineColor: "rgba(191, 209, 255, 0.5)",
  pointLineColor: "rgba(191, 209, 255, 0.3)",
  fillColor: "#DAE3F8",
  selectionColor: "#4972DF"
})

// 图片设置
const imageConfig = reactive({
  rotate: 0,
  scale: 100,
  opacity: 100
})

// 拼图实例
let pt = null
// 当前选中的多边形
const selectedPolygon = ref(null)

// 是否已上传图片
const hasImages = ref(false)

// 模板列表数据
const templateList = [
  {
    title: 2,
    list: [
      {
        icon: '/images/template-puzzle/nav/2_01_0.png',
        activeIcon: '/images/template-puzzle/nav/2_01_1.png',
        templateUrl: '/images/template-puzzle/template/01.png',
        type: 'normal'
      },
      {
        icon: '/images/template-puzzle/nav/2_02_0.png',
        activeIcon: '/images/template-puzzle/nav/2_02_1.png',
        templateUrl: '/images/template-puzzle/template/02.png',
        type: 'normal'
      },
      {
        icon: '/images/template-puzzle/nav/2_03_0.png',
        activeIcon: '/images/template-puzzle/nav/2_03_1.png',
        templateUrl: '/images/template-puzzle/template/03.png',
        type: 'normal'
      },
      {
        icon: '/images/template-puzzle/nav/2_04_0.png',
        activeIcon: '/images/template-puzzle/nav/2_04_1.png',
        templateUrl: '/images/template-puzzle/template/04.png',
        type: 'normal'
      }
      // ... 其他模板
    ]
  }
  // ... 其他格数
]

// 计算过滤后的模板列表
const filteredTemplates = computed(() => {
  return templateList
    .filter(t => t.title === selectedNav.value)
    .flatMap(t => t.list)
    .filter(t => showBizarre.value ? t.bizarre : !t.bizarre)
})

// 文件输入引用
const fileInput = ref(null)
const canvas = ref(null)

// 修改触发文件选择的方法
const triggerUpload = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 初始化画布
const initCanvas = async () => {
  if (!canvas.value) return
  
  try {
    pt = await pintu.create({
      canvas: canvas.value,
      ...canvasConfig,
      ondrop: handleDrop,
      onclick: handleClick,
      onselect: handleSelect
    })
  } catch (error) {
    console.error('初始化画布失败:', error)
  }
}

// 选择导航
const selectNav = (nav) => {
  selectedNav.value = nav
}

// 切换异形显示
const toggleBizarre = () => {
  showBizarre.value = !showBizarre.value
}

// 选择模板
const selectTemplate = async (template) => {
  selectedTemplate.value = template
  
  // 加载模板图片
  const img = new Image()
  img.src = template.templateUrl
  img.onload = () => {
    // 创建模板数据
    const templateData = {
      image: img,
      width: img.width,
      height: img.height
    }
    
    // 更新画布
    pt.config({ template: templateData })
  }
}

// 处理图片拖放
const handleDrop = (polygon, files) => {
  if(files[0]) {
    setImage(files[0], polygon)
  }
}

// 处理点击添加图片
const handleClick = (polygon) => {
  if (!fileInput.value) return
  
  selectedPolygon.value = polygon
  triggerUpload()
}

// 处理选中多边形
const handleSelect = (polygon) => {
  selectedPolygon.value = polygon
  if(polygon && polygon.image) {
    imageConfig.rotate = polygon.rotate || 0
    imageConfig.scale = (polygon.scale || 1) * 100
    imageConfig.opacity = (polygon.opacity || 1) * 100
  }
}

// 处理文件上传
const handleFileUpload = (e) => {
  const files = Array.from(e.target.files)
  if(files.length > 0) {
    // 如果没有选中的多边形，创建一个新的
    if (!selectedPolygon.value && pt) {
      pt.createPolygons({})  // 创建默认多边形
      selectedPolygon.value = pt.polygons[0]
    }
    setImage(files[0])
    hasImages.value = true
  }
}

// 设置图片
const setImage = async (file, polygon = selectedPolygon.value) => {
  // 确保有有效的多边形
  if (!polygon) {
    console.error('没有选中的多边形')
    return
  }

  const reader = new FileReader()
  reader.onload = async (e) => {
    const img = new Image()
    img.src = e.target.result
    img.onload = () => {
      polygon.setImage(img)
      // 设置初始值
      polygon.rotate = imageConfig.rotate
      polygon.scale = imageConfig.scale / 100
      polygon.opacity = imageConfig.opacity / 100
      pt.render()
    }
  }
  reader.readAsDataURL(file)
}

// 替换图片
const replaceImage = () => {
  triggerUpload()
}

// 删除图片
const deleteImage = () => {
  if(selectedPolygon.value) {
    selectedPolygon.value.setImage(null)
    pt.render()
    selectedPolygon.value = null
  }
}

onMounted(() => {
  // 确保 DOM 元素已经挂载
  if (canvas.value && fileInput.value) {
    initCanvas()
  }
})
</script>

<style lang="scss" scoped>
.template-puzzle {
  display: flex;
  height: 100%;
  padding: 20px;
  gap: 20px;
}

.left-panel {
  width: 240px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  
  .template-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    
    .nav-item {
      padding: 8px 16px;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
      
      &.active {
        background: #4972DF;
        color: white;
      }
    }
  }
  
  .template-list {
    flex: 1;
    overflow-y: auto;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
    
    .template-item {
      aspect-ratio: 1;
      border: 2px solid transparent;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;
      
      &:hover {
        border-color: #4972DF;
        opacity: 0.8;
      }
      
      &.active {
        border-color: #4972DF;
        
        img {
          transform: scale(1.05);
        }
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        transition: transform 0.2s ease;
      }
    }
  }
}

.canvas-area {
  flex: 1;
  position: relative;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .upload-tip {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    
    .tip-text {
      margin-bottom: 20px;
      color: #999;
    }
    
    .upload-btn {
      padding: 8px 16px;
      background: #4972DF;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
  }
}

.right-panel {
  width: 300px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  
  .setting-item {
    margin: 15px 0;
  }
  
  .operation-btns {
    display: flex;
    gap: 10px;
    margin-top: 20px;
    
    button {
      flex: 1;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background: white;
      cursor: pointer;
      
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>